package com.cy.store.service.impl;

import com.cy.store.domain.Cart;
import com.cy.store.mapper.CartMapper;
import com.cy.store.mapper.ProductMapper;
import com.cy.store.service.ICartService;
import com.cy.store.service.ex.AccessDeniedException;
import com.cy.store.service.ex.CartNoFoundException;
import com.cy.store.service.ex.InsertException;
import com.cy.store.service.ex.UpdateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author Administrator
 * @version 1.0
 * @description: TODO
 * @date 2025/3/1 09:25
 */
@Service
public class CartServiceImpl implements ICartService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductMapper productMapper;

    @Override
    public void addToCart(Integer uid, Integer pid, Integer num, String username) {
        Cart cart = cartMapper.findByUidAndPid(uid, pid);
        Integer rows = 0;
        if (cart != null) {
             num = cart.getNum() + num;
            rows = cartMapper.updateNumByCid(cart.getId(), num, username, new Date());
            if (rows != 1) {
                throw new UpdateException("更新数据时产生未知的异常");
            }
        } else {
            cart = new Cart();
            cart.setUid(uid);
            cart.setPid(pid);
            cart.setNum(num);
            Long price = productMapper.findById(pid).getPrice();
            cart.setPrice(price);
            cart.setCreatedTime(new Date());
            cart.setModifiedUser(username);
            cart.setModifiedTime(new Date());
            cart.setCreatedUser(username);
            rows = cartMapper.insert(cart);
            if (rows != 1) {
                throw new InsertException("插入数据时产生未知的异常");
            }

        }

    }
    public Integer addNum(Integer cid, Integer uid, String username) {
        Cart cart = cartMapper.findByCid(cid);
        if(cart == null){
            throw new CartNoFoundException("尝试访问的购物车数据不存在");
        }
        if(!uid.equals(cart.getUid())){
            throw new AccessDeniedException("非法访问");
        }
        Integer num = cart.getNum() + 1;
        Integer rows = cartMapper.updateNumByCid(cid, num, username, new Date());
        if(rows != 1){
            throw new UpdateException("更新数据时产生未知的异常");
        }
        return num;
    }
}
